﻿using SHKF.B2C.Model;
using SHKF.B2C.Model.Dto;
using SHKF.B2C.Model.Dto.Center;
using SHKF.B2C.Model.Dto.WorkingCenter;
using SHKF.B2C.Model.Entity.Center;
using SHKF.B2C.Model.Entity.WorkingCenter;
using SHKF.B2C.Model.Req;
using SHKF.B2C.YouZanYun.Model.Inter.CategoryPropertys;
using SHKF.B2C.YouZanYun.Model.Inter.Item;
using System;
using System.Collections.Generic; 
using System.Threading.Tasks;
using System.Windows; 
using WQDSkin.Forms.Component;  
 

namespace SHKF.B2C.Mannage.AdminUI.View.CenterInfo.Product
{
    /// <summary>
    /// frmProductEdit.xaml 的交互逻辑
    /// </summary>
    public partial class frmProductEdit : BasePage
    { 
        public frmProductEdit()
        {
            InitializeComponent();
        }

        private void BasePage_Loaded(object sender, RoutedEventArgs e)
        {
            this.LoadMapData();
            this.LoadRelatedData();
        }

        #region 有赞云
        private async void btnYZYBind_Click(object sender, RoutedEventArgs e)
        {
            ProductInfo product = (ProductInfo)this.DataContext;
            frmSearchProductYZY frmSearch = new frmSearchProductYZY();
            frmSearch.CompanySN = product.CompanySN;
            if (frmSearch.ShowDialog() == true)
            {
                //ProductInfoMapEntity map = new ProductInfoMapEntity();
                //map.Platform = PlatformEnum.YouZanYun;
                //map.ProductSN = product.ProductSN;
                //map.app_poi_code = frmSearch.SelectData.item_id;
                //map.ItemNo = frmSearch.SelectData.item_no;

                ProductInfoMapListDto dto = await AddProductMap(product.Upc, 
                    frmSearch.SelectData.item_id.ToString());
                if (dto.error == null)
                {
                    ReLoadMapData(dto);
                }
                else
                {
                    MessageBox.Show(dto.error.msg);
                }
            }
        }

  
        private async void btnYZYAdd_Click(object sender, RoutedEventArgs e)
        {
            ProductInfo product = (ProductInfo)this.DataContext;

            string authority_id = "";
            DataDto dto = await GL.HttpClientManage.ShopGetKdtId(product.CompanySN);
            if (dto.error == null)
            {
                authority_id = dto.data;
            }

            try
            {
                frmItemAddYZY frmYzy = new frmItemAddYZY();
                frmYzy.authority_id = authority_id;

                if (frmYzy.ShowDialog() == true)
                {
  
                    //加载总部Id 
                    ParamItemRequest paramItem = new ParamItemRequest();

                    Param param = new Param();

                    paramItem.param = param;
                    param.image_ids = frmYzy.media_id;

                    param.title = "[辅仁]感冒灵颗粒10g*10袋/盒";
                    param.quantity = 0;

                    param.item_no = product.ID;
                    param.node_kdt_id = int.Parse(authority_id);

                    //配送
                    param.item_delivery_param = new item_delivery_param();

                    //类目
                    category_param category_Param = new category_param();
                    category_properties category_Properties = new category_properties();
                    category_Properties.publics = await publics(product, authority_id, frmYzy.leaf_category_id);

                    category_Properties.leaf_category_id = frmYzy.leaf_category_id; //新版商品类目（V4版本）叶子类目id
                    category_Param.category_properties = category_Properties;
                    param.category_param = category_Param;

                    ItemResult result = await GL.HttpClientYzy.ItemAdd(authority_id, paramItem);
                    if (!result.success)
                    {
                        MessageBox.Show(result.message);
                    }
                    else
                    {
                        //上传时不用编码，因为可以直接在产品表中查找
                        ProductInfoMapListDto dto2 = await AddProductMap(product.Upc, result.data.item_id.ToString());
                        if (dto2.error != null)
                        {
                            MessageBox.Show(dto2.error.msg);
                        }
                        ReLoadMapData(dto2); 
                    }
 
                    MessageBox.Show("上传成功!");

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private async  Task<ProductInfoMapListDto> AddProductMap(string Upc,string app_medicine_code)
        {
            ProductInfoMapEntity map = new ProductInfoMapEntity();
            map.Platform = PlatformEnum.YouZanYun;
            map.Upc = Upc;
            map.app_medicine_code = app_medicine_code;
            map.FKSN = this.Data.SN;
            ProductInfoMapListDto dto = await GL.HttpClientManage.ProductMapSave(map); 
            return dto; 
        }

        private async Task<List<publics>> publics(ProductInfo product, string authority_id, long id)
        { 
            List<publics> _publics = new List<publics>();
            CategoryPropertysResult result = await GL.HttpClientYzy.GetCategoryById(authority_id, id);

            if (result.success && result.data != null && result.data.public_propertys != null
                && result.data.public_propertys.Count > 0)
            {
                foreach (Public_Propertys pro in result.data.public_propertys)
                {
                    Property property = pro.property;

                    List<string> val_names = new List<string>();
                    if (property.name == "产品剂型")
                    {
                        val_names.Add(product.Model);
                    }
                    else if (property.name == "生产企业")
                    {
                        val_names.Add(product.Manufacturer);
                    }
                    else if (property.name == "批准文号")
                    {
                        val_names.Add(product.LiceseId);
                    }
                    else if (property.name == "有效期")
                    {
                        val_names.Add(product.Validate.ToString());
                    }
                    else if (property.name.Contains("通用名"))
                    {
                        val_names.Add(product.CommonTitle);
                    }
                    else if (property.name.Contains("规格"))
                    {
                        val_names.Add(product.Spec);
                    }
                    else if (property.name.Contains("贮藏条件"))
                    {
                        val_names.Add(product.ConditionOfStorage);
                    }
                    else if (property.name.Contains("单位"))
                    {
                        val_names.Add(product.Unit);
                    }
                    else if (property.name.Contains("追溯码"))
                    {
                        val_names.Add(product.Upc);
                    }

                    _publics.Add(new publics() { id = property.id, val_names = val_names });
                }
            }
            else
            {
                MessageBox.Show(result.message); 
            }

            return _publics;
        }

        #endregion


        private void btnRef_Click(object sender, RoutedEventArgs e)
        {
            LoadMapData();
        } 
        private async void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (this.dgvMap.SelectedItems.Count > 0)
            {
                if (MessageBox.Show("请确认是否要删除", "删除提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    ProductInfoMapEntity info = (ProductInfoMapEntity)this.dgvMap.SelectedItem;
                    ProductInfoMapListDto dto = await GL.HttpClientManage.ProductMapDelete(info.SN);
                    if (dto.error == null)
                    {
                        this.dgvMap.ItemsSource = dto.data;
                        LoadToolEnable(dto);
                    }
                    else
                    {
                        MessageBox.Show(dto.error.msg);
                    }
                }
            }
        }

        private async void LoadMapData()
        {
            ProductInfoEntity productInfo = (ProductInfoEntity)this.DataContext;

            ProductInfoMapListDto dto = await GL.HttpClientManage.ProductMapQuery(productInfo.SN);
            if (dto.error == null)
            {
                this.dgvMap.ItemsSource = dto.data;

                LoadToolEnable(dto);
            }
            else
            {
                MessageBox.Show(dto.error.msg);
            }
        }
        private void ReLoadMapData(ProductInfoMapListDto dto)
        {
            this.dgvMap.ItemsSource = dto.data;
            this.LoadToolEnable(dto);
        }


        private void LoadToolEnable(ProductInfoMapListDto dto)
        {
            if (dto.data.Count == 0)
            {
                btnYzyBind.IsEnabled = true;
                btnYZYAdd.IsEnabled = true;
            }
            else
            {
                var yzyInfo = dto.data.Find(oo => oo.Platform == PlatformEnum.YouZanYun);
                btnYzyBind.IsEnabled = yzyInfo == null;
                btnYZYAdd.IsEnabled = yzyInfo == null;
            }
        }

        #region 分仓产品映射

        private async void LoadRelatedData()
        {
            //long productVSN = this.Data.ProductSN;
            //ProductInfoRelatedListDto dto = await GL.HttpClientManage.QueryProductRelatedList(productVSN);
            //if( dto.error == null)
            //{
            //    this.dgvProductRelated.ItemsSource = dto.data;
            //}
            //else
            //{
            //    MessageBox.Show(dto.error.msg);
            //}
        }

        private void btnAddRelated_Click(object sender, RoutedEventArgs e)
        {
            //frmSearchProductRelated win = new frmSearchProductRelated();
            //win.ProductVSN = this.Data.ProductSN;

            //if ( win.ShowDialog() == true )
            //{
            //    LoadRelatedData();
            //}
        }

        private async void btnDeleteRelated_Click(object sender, RoutedEventArgs e)
        {
            if (this.dgvProductRelated.SelectedItem != null)
            {
                if (MessageBox.Show("请确认是否要删除", "删除提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    ProductInfoRelatedEntity info = (ProductInfoRelatedEntity)this.dgvProductRelated.SelectedItem;
                    DataDto dto = await GL.HttpClientManage.DeleteProductRelated(info.SN);
                    if (dto.error == null)
                    {
                        this.LoadRelatedData();
                    }
                    else
                    {
                        MessageBox.Show(dto.error.msg);
                    }
                }
            }
        }

        private void btnRefRelate_Click(object sender, RoutedEventArgs e)
        {
           this.LoadRelatedData();
        }

        #endregion

        private ProductInfoEntity Data
        {
            get
            {
                ProductInfoEntity product = (ProductInfoEntity)this.DataContext;
                return product;
            }
        } 
    }
}
